#include "video.h"

Video::Video(QSize const size) : cvimage(NULL), inRefresh(false), window_title(NULL)
{
    imageSize = size;
    windowsSize = size;
    window_title = "Video display";
    this->setMinimumSize(windowsSize);
    this->setMaximumSize(windowsSize);
}

Video::~Video()
{
    if(cvimage){
        cvReleaseImage(&cvimage);
        cvimage=NULL;
    }
    if(window_title){
        free(window_title);
    }
}

void Video::run()
// On cree une fenetre dans laquelle l'image sera rafraichie toutes les qlq ms.
{
    this->show();

    image = QImage(imageSize, QImage::Format_RGB32);
    timer = new QTimer();
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
    timer->start(40);
}

void Video::terminate()
// Destruction de la fenetre
{
    this->hide();
    killTimer(idTimer);
}

void Video::closeEvent(QCloseEvent *event)
// On envoi un signal lors de la fermeture de la fenetre
{
    emit closed();
}

void Video::refresh()
//     On affiche l'image dans une fenêtre
{
    if(inRefresh){
        return;
    }
    inRefresh=true;
    if(cvimage) {
        cvReleaseImage(&cvimage);
        cvimage=NULL;
    }
    locker.lock();
    if(!cvimageinter){
        locker.unlock();
        return;
    }
    cvimage = cvCloneImage(cvimageinter);
    locker.unlock();

    // On converti l'image opencv cvimage en image Qt QImage
    int cvIndex, cvLineStart;
    cvIndex = 0; cvLineStart = 0;
    for (int y = 0; y < cvimage->height; y++) {
        unsigned char red,green,blue;
        cvIndex = cvLineStart;
        for (int x = 0; x < cvimage->width; x++) {
            red = cvimage->imageData[cvIndex+2];
            green = cvimage->imageData[cvIndex+1];
            blue = cvimage->imageData[cvIndex+0];

            image.setPixel(x,y,qRgb(red, green, blue));
            cvIndex += 3;
        }
        cvLineStart += cvimage->widthStep;
    }
    // On met a jour l'image affichee dans le QLabel
    this->setPixmap(QPixmap::fromImage(image.scaled(windowsSize)));
    inRefresh=false;
}
